/**
 * sidebarMenu
 * @author Brant Liu
 * @email lbf1988@qq.com
 * @date 2019/9/26
 * @version 1.0.0
 */
layui.define(['jquery'], function(exports){
    "use strict";

    var $ = layui.jquery;

    var _sidebarMenu = {};

    _sidebarMenu.version = '1.0.0';

    $.sidebarMenu = function(menu) {
        var animationSpeed = 300, subMenuSelector = '.sidebar-submenu', menuSelected = ".selected";

        $(menu).on('click', 'li a', function(e) {
            var $this = $(this);
            var checkElement = $this.next();

            if (checkElement.is(subMenuSelector) && checkElement.is(':visible')) {
                checkElement.slideUp(animationSpeed, function() {
                    $this.parent().find(subMenuSelector).hide().removeClass('menu-open');
                });
                $this.parent().removeClass("active");
                $this.parent().find("li").removeClass("active");
            }

            //If the menu is not visible
            else if ((checkElement.is(subMenuSelector)) && (!checkElement.is(':visible'))) {
                //Get the parent menu
                var parent = $this.parents('ul').first();
                //Close all open menus within the parent
                var ul = parent.find('ul:visible').slideUp(animationSpeed);
                //Remove the menu-open class from the parent
                ul.removeClass('menu-open');
                //Get the parent li
                var parent_li = $this.parent("li");

                //Open the target menu and add the menu-open class
                checkElement.slideDown(animationSpeed, function() {
                    //Add the class active to the parent li
                    checkElement.addClass('menu-open');
                    parent.find('li.active').removeClass('active');
                    parent_li.addClass('active');
                });
            }

            //if this isn't a link, prevent the page from being redirected
            if (checkElement.is(subMenuSelector)) {
                e.preventDefault();
            }

            //if this is a link
            if(checkElement.length === 0){
                $(menu).find(menuSelected).removeClass(menuSelected.substring(1));
                $this.parent().addClass(menuSelected.substring(1));

                var $siblings = $this.parent().siblings();
                $siblings.removeClass("active").find('ul:visible').slideUp(animationSpeed);
                $siblings.find(subMenuSelector).removeClass("menu-open");
            }
        });
    };

    _sidebarMenu.render = function(menu){
        $.sidebarMenu(menu);
    };

    exports('sidebarMenu', _sidebarMenu);
});